package org.example.controller;

import org.example.config.PropertiesConfig;
import org.example.param.TagAddParam;
import org.example.param.TagDeleteParam;
import org.example.param.TagFuzzyParam;
import org.example.param.TagUpdateParam;
import org.example.service.TagService;
import org.example.utils.FileUploadUtil;
import org.example.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/tag")
public class TagController {
    @Resource
    private TagService tagService;

    @GetMapping("/all")
    @PreAuthorize("permitAll()")
    public Result all(){
        return tagService.all();
    }

    @PostMapping("/add")
    @PreAuthorize("hasAnyRole('admin')")
    public Result add(@RequestBody @Validated TagAddParam tagAddParam){
        return tagService.add(tagAddParam);
    }

    @PostMapping("/findTagByName")
    @PreAuthorize("hasAnyRole('admin')")
    public Result findTagByName(@RequestBody Map<String,String> map){
        String tagName = map.get("tagName");
        return tagService.findTagByName(tagName);
    }

    @PostMapping("/findTagById/{id}")
    @PreAuthorize("permitAll()")
    public Result findTagById(@PathVariable("id") Long id){
        return tagService.findTagById(id);
    }

    @PostMapping("/delete")
    @PreAuthorize("hasAnyRole('admin')")
    public Result delete(@RequestBody @Validated TagDeleteParam tagDeleteParam){
        return tagService.delete(tagDeleteParam);
    }

    @PostMapping("update")
    @PreAuthorize("hasAnyRole('admin')")
    public Result update(@RequestBody @Validated TagUpdateParam tagUpdateParam){
        return tagService.update(tagUpdateParam);
    }

    /**
     * 模糊查询
     */
    @PostMapping("/fuzzy")
    @PreAuthorize("permitAll()")
    public Result fuzzy(@RequestBody TagFuzzyParam tagFuzzyParam){
        return tagService.fuzzy(tagFuzzyParam);
    }

    @PostMapping("/uploadAvatar")
    @PreAuthorize("hasAnyRole('admin')")
    public Result upload(@RequestParam("image")MultipartFile file) throws IOException {
        String url = FileUploadUtil.upload(PropertiesConfig.getUploadTagDir(), file, FileUploadUtil.IMAGE_ALLOWED_EXTENSION);
        return Result.success(FileUploadUtil.transformUrl(url));
    }

    @PostMapping("hot")
    @PreAuthorize("permitAll()")
    public Result hot(@RequestBody(required = false) Map<String,Integer> map){
        if (map == null) map = new HashMap<>();
        Integer limit = map.get("limit");
        return tagService.hot(limit);
    }


}
